#include "Host.h"
#include "NodeServer.h"
#include "Game.h"
#include "cache.h"
#include "ActionTopic.h"


CHostBase* CreateHost()
{
	CHost* pHost = new CHost();
	return pHost;
}

std::string GetLogFileName()
{
	return "tgbot";
}

CHost::CHost()
{
	this->m_bCacheConnOK = false;
}

CHost::~CHost()
{
}


void CHost::Init()
{
	// 初始化服务对象
	this->m_pNode = GetNodeServer();
	this->m_pGame = new CGameServer();
	this->m_pGame->m_pHost = this;
	if (!this->m_pGame->InitGame())
	{
		delete m_pGame;
		m_pGame = NULL;
		exit(-1);
		return;
	}

	
	// 订阅php配置更新事件
	ActionTopic::Init();

	
	// 设置节点服务Redis
	vector<CONFITEM> items;
	CONFITEM conf_item;

	conf_item.type = MASTER_CONF_REDIS;
	conf_item.name = "config_cache";
	items.push_back(conf_item);

	SpiderEvent ev;
	ev.evID = NODE_EV_SET_CACHE;
	ev.evParam.ptr = &items;
	m_pNode->ProcEvent(NODE_EV_SET_CACHE, &ev);

	
	// 设置节点服务类型
	ev.evID = NODE_EV_SET_TYPE;
	ev.evParam.iParam = SERVER_TYPE_TG_BOT;
	m_pNode->ProcEvent(NODE_EV_SET_TYPE, &ev);

}


int CHost::OnBYTimeOut(int Timerid)
{
	return 0;
}

int CHost::ProcEvent(int ev_id, SpiderEvent* pEvent)
{
	// 处理事件发布
	if (HOST_EV_GAME_INIT == ev_id)
	{
		// 主线程，附加epoll
		this->InitMtSend();

		// 先触发HOST_EV_CACHE_CONN_SUCCESS->加载redis；再触发HOST_EV_GAME_INIT->故在此执行redis加载配置
		m_pGame->LoadCfgToMap();
	}
	else if (HOST_EV_CACHE_CONN_SUCCESS == ev_id)
	{
		CONFITEM* item = (CONFITEM*)pEvent->evParam.ptr;
		if (MASTER_CONF_REDIS == item->type)
		{
			if ("config_cache" == item->name)
			{
				RedisClient* pRedis = m_pNode->GetCacheClient(item->name);
				m_pGame->m_dbHandler.m_configRedis = pRedis;
				if (NULL == m_pGame->m_dbHandler.m_configRedis)
				{
					log_error("Get Redis Client Failed, CONFITEM->name: %s;", item->name.c_str());
					return -1;
				}
				log_debug("Get Redis Client Success");
			}
		}
		this->m_bCacheConnOK = true;

		// 加载redis配置数据
		do {
			if (!m_pGame->m_dbHandler.CheckServerReady()) {
				log_error("Check Server Ready Failed, Redis Client is null !!!");
				break;
			}

			if (!m_pGame->m_dbHandler.LoadTgBotCfg(TG_BOT_CONFIG)) {
				log_error("Load TgBotConfig Failed !!!");
				break;
			}
			log_error("Load TgBotConfig Success !!!");
		} while (false);
	}
	
	return 0;
}


int CHost::ProcPacket(NETInputPacket* inputPkg, SocketHandler* pSocketHandler)
{
	if (NULL != m_pGame && this->m_bCacheConnOK)
	{
		return m_pGame->ProcessPacket(pSocketHandler, inputPkg);
	}
	return 0;
}